package com.ltmall.api.dao.impl;

import com.ltmall.api.bean.*;
import com.ltmall.api.dao.IOrderDAO;
import com.ltmall.api.entity.JsonOrder;
import com.ltmall.api.entity.info.MemberDeductibleInfo;
import com.ltmall.api.manager.*;
import com.ltmall.api.parse.GoodsParse;
import com.ltmall.api.rule.CSG;
import com.ltmall.api.rule.OrderRule;
import com.ltmall.api.util.PageUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class OrderDAO extends BaseEntityDAO<Order> implements IOrderDAO {
    private CartManager         cartManager;
    private OrderManager        orderManager;
    private LogisticManager     logiManager;
    private GoodsManager        goodsManager;
    private AccountManager      accountManager;
    private MembershipManager   membershipManager;
    private AccountDAO          aDAO;
    private DirectSupplyManager directoryManager;

    public void setDirectoryManager(DirectSupplyManager directoryManager) {
        this.directoryManager = directoryManager;
    }

    private Logger logger = LogManager.getLogger(OrderDAO.class);

    public boolean addOrderContent(OrderContent oContent) {
        oContent.setOpTime(System.currentTimeMillis());// 设置时间
        try {
            getHibernateTemplate().persist(oContent);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean delOrder(int orderID) {
        // TODO Auto-generated method stub
        String hql = "update Order orde set orde.show = ? where orde.orderID = ? and orde.station= 6";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, 1);
            query.setParameter(1, orderID);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean delOrderContent(int orderID) {
        // TODO Auto-generated method stub
        String hql = "delete OrderContent oContent where oContent.orderID = ?";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, orderID);
            int temp = query.executeUpdate();
            if (temp >= 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @SuppressWarnings("unchecked")
    public List<Order> orderList(final int userID, final int station, final PageUtil page) {
        // TODO Auto-generated method stub
        String tempHQL;
        if (station == 0) {// 获取全部订单
            /*
             * 全部订单指的是不为0的订单
             */
            tempHQL = "from Order orde where orde.userID = ? and orde.station != ? and orde.show=0 order by orde.opTime desc";
        } else {
            tempHQL = "from Order orde where orde.userID = ? and orde.station = ?  and orde.station!=0  and orde.show=0 order by orde.opTime desc";
        }
        final String HQL = tempHQL;
        @SuppressWarnings("rawtypes")
        List<Order> list = this.getHibernateTemplate().execute(new HibernateCallback<List>() {
            public List doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createQuery(HQL);
                query.setParameter(0, userID);
                query.setParameter(1, station);
                // 分页
                query.setFirstResult((page.getCur_page() - 1) * page.getNumPerPage())
                    .setMaxResults(page.getNumPerPage());
                return query.list();
            }
        });
        return list;
    }

    @SuppressWarnings("unchecked")
    public List<Order> diretorPrivilegeOrderList(final int userID) {
        // TODO Auto-generated method stub
        String tempHQL = "from Order orde where orde.userID = ? and orde.feeDirector != 0 and orde.station in (2,3,4,5,6,10)  and orde.show=0 order by orde.opTime desc";
        final String HQL = tempHQL;
        @SuppressWarnings("rawtypes")
        List<Order> list = this.getHibernateTemplate().execute(new HibernateCallback<List>() {
            public List doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createQuery(HQL);
                query.setParameter(0, userID);
                return query.list();
            }
        });
        return list;
    }

    public boolean updateOrderStation(int orderID, int station) {
        // TODO Auto-generated method stub
        String hql = "update Order orde set orde.station = ?" + "where orde.orderID = ?";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, station);
            query.setParameter(1, orderID);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public List<OrderContent> getOrderContent(final int orderID) {
        // TODO Auto-generated method stub
        final String HQL = "from  OrderContent oc where oc.orderID =?";
        List<OrderContent> list = this.getHibernateTemplate().execute(
            new HibernateCallback<List>() {
                public List doInHibernate(Session session) throws HibernateException, SQLException {
                    Query query = session.createQuery(HQL);
                    query.setParameter(0, orderID);
                    return query.list();
                }
            });
        return list;
    }

    public boolean addOrderLogistic(OrderLogistic oLogistic) {
        oLogistic.setOpTime(System.currentTimeMillis());// 设置时间
        try {
            getHibernateTemplate().persist(oLogistic);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean updateOrderFee(int orderID, double fee) {
        // TODO Auto-generated method stub
        String hql = "update Order orde set orde.fee = ?" + "where orde.orderID = ?";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, fee);
            query.setParameter(1, orderID);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean updateOrderFeeDirector(int orderID, double fee) {
        String hql = "update Order orde set orde.feeDirector = ?" + "where orde.orderID = ?";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, fee);
            query.setParameter(1, orderID);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @SuppressWarnings("rawtypes")
    public Order getOrder(int orderID) {
        List list = this.getHibernateTemplate().find("from Order orde where orde.orderID =?",
            new Object[] { orderID });
        if (list.size() > 0) {
            return (Order) list.get(0);
        }
        return null;
    }

    public boolean orderUpdate(float wxFee, float zfbFee, float couponFee, float giftcardFee,
                               String message, int station, int orderID, int transactionType,
                               String invoice, String congratulations, String deliveryTime) {
        // TODO Auto-generated method stub
        String hql = "update Order orde set orde.wxFee=?,orde.zfbFee=?,orde.couponFee = ?,orde.giftcardFee=?,orde.station = ?,orde.message = ?,orde.opTime = ?,orde.transactionType= ?,orde.invoice=?,orde.congratulations=?,orde.deliveryTime = ?"
                     + " where orde.orderID = ?";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, wxFee);
            query.setParameter(1, zfbFee);
            query.setParameter(2, couponFee);
            query.setParameter(3, giftcardFee);

            query.setParameter(4, station);
            query.setParameter(5, message);
            query.setParameter(6, System.currentTimeMillis());
            query.setParameter(7, transactionType);
            query.setParameter(8, invoice);
            query.setParameter(9, congratulations);
            query.setParameter(10, deliveryTime);
            query.setParameter(11, orderID);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean addComment(Comment comment) {
        comment.setOpTime(System.currentTimeMillis());// 设置时间
        try {
            getHibernateTemplate().persist(comment);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public OrderLogistic getOrderLogistic(int orderID) {
        List list = this.getHibernateTemplate().find(
            "from OrderLogistic logi where logi.orderID =?", new Object[] { orderID });
        if (list.size() > 0) {
            return (OrderLogistic) list.get(0);
        }
        return null;
    }

    @SuppressWarnings("rawtypes")
    public boolean isComment(int userID, int orderID, int goodsID, String format) {
        List list = this
            .getHibernateTemplate()
            .find(
                "from Comment co where co.orderID =? and co.goodsID = ? and co.goodsFormat = ?and co.userID = ? ",
                new Object[] { orderID, goodsID, format, userID });
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    public boolean addRefund(Refund refund) {
        refund.setOpTime(System.currentTimeMillis());// 设置时间
        try {
            getHibernateTemplate().persist(refund);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @SuppressWarnings("rawtypes")
    public List<Refund> refundList(final int userID, final PageUtil page) {
        // TODO Auto-generated method stub
        final String HQL = "from Refund refund where refund.userID = ? order by refund.opTime desc";
        @SuppressWarnings("unchecked")
        List<Refund> list = this.getHibernateTemplate().execute(new HibernateCallback<List>() {
            public List doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createQuery(HQL);
                query.setParameter(0, userID);
                // 分页
                query.setFirstResult((page.getCur_page() - 1) * page.getNumPerPage())
                    .setMaxResults(page.getNumPerPage());
                return query.list();
            }
        });
        return list;
    }

    @SuppressWarnings("rawtypes")
    public ActivityPrice getActivityPrice(int goodsID, String format) {
        long cTime = System.currentTimeMillis();
        List list = this
            .getHibernateTemplate()
            .find(
                "from ActivityPrice ap where ap.goodsID =? and ap.format = ? and ap.startTime<=? and ap.endTime>=?",
                new Object[] { goodsID, format, cTime, cTime });
        if (list.size() > 0) {
            return (ActivityPrice) list.get(0);
        }
        return null;
    }

    public boolean addTradeNo(TradeNo no) {
        // TODO Auto-generated method stub
        no.setOpTime(System.currentTimeMillis());// 设置时间
        try {
            getHibernateTemplate().persist(no);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @SuppressWarnings("rawtypes")
    public TradeNo getTradeNo(String no) {
        List list = this.getHibernateTemplate().find("from TradeNo tn where tn.outTradeNo =?",
            new Object[] { no });
        if (list.size() > 0) {
            return (TradeNo) list.get(0);
        }
        return null;
    }

    public boolean tradeNoUpdate(TradeNo to) {
        String hql = "update TradeNo tn set tn.orderIDs = ?, tn.userID = ?, tn.tradeNo = ?, tn.totalFee = ? where tn.outTradeNo = ?";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, to.getOrderIDs());
            query.setParameter(1, to.getUserID());
            query.setParameter(2, to.getTradeNo());
            query.setParameter(3, to.getTotalFee());
            query.setParameter(4, to.getOutTradeNo());
            int ret = query.executeUpdate();
            if (ret == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean addOrderTime(OrderTime orderTime) {
        try {
            getHibernateTemplate().persist(orderTime);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean updateOrderTime(int orderID, int type, long time) {
        // TODO Auto-generated method stub
        /*
         * 1：下单时间； 2：支付时间； 3：发货时间 4：物流确认收获时间 5：买家确认收获时间 6：买家申请退款时间 7：商家确认退款时间
         * 8：平台退款时间
         */
        String hql = "";
        switch (type) {
            case 1:
                hql = "update OrderTime ot set ot.orderCommitTime = ? where ot.orderID = ?";
                break;
            case 2:
                hql = "update OrderTime ot set ot.payTime = ? where ot.orderID = ?";
                break;
            case 3:
                hql = "update OrderTime ot set ot.deliveryTime = ? where ot.orderID = ?";
                break;
            case 4:
                hql = "update OrderTime ot set ot.pressConfirmTime = ? where ot.orderID = ?";
                break;
            case 5:
                hql = "update OrderTime ot set ot.clientConfirmTime = ? where ot.orderID = ?";
                break;
            case 6:
                hql = "update OrderTime ot set ot.commentTime = ? where ot.orderID = ?";
                break;
        }

        try {
            Session session = getSession();
            Query query = session.createQuery(hql);
            query.setParameter(0, time);
            query.setParameter(1, orderID);
            int tag = query.executeUpdate();
            if (tag == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public OrderTime getOrderTime(int orderID) {
        List list = this.getHibernateTemplate().find("from OrderTime ot where ot.orderID =?",
            new Object[] { orderID });
        if (list.size() > 0) {
            return (OrderTime) list.get(0);
        }
        return null;
    }

    public boolean addShopClient(ShopClient shopClient) {
        shopClient.setOpTime(System.currentTimeMillis());// 设置时间
        try {
            getHibernateTemplate().persist(shopClient);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @SuppressWarnings("rawtypes")
    public boolean shopClientExist(int shopID, int userID) {
        List list = this.getHibernateTemplate().find(
            "from ShopClient sc where sc.shopID =? and sc.userID = ?",
            new Object[] { shopID, userID });
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    public boolean updateOrderStationAndTransaction(int orderID, int station, int transType,
                                                    String transNumber) {
        String hql = "update Order orde set orde.station = ?,orde.transactionType = ?,orde.transactionNumber =?"
                     //         + "where orde.orderID = ? and orde.station=1";
                     + "where orde.orderID = ? ";

        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, station);
            query.setParameter(1, transType);
            query.setParameter(2, transNumber);
            query.setParameter(3, orderID);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean deleteCouponCount(int userID, float fee) {
        // TODO Auto-generated method stub
        String hql = "update WalletGiftCardCount wgcc set wgcc.money = wgcc.money-?"
                     + " where wgcc.userID = ?";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, fee);
            query.setParameter(1, userID);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean updateActivityGoodsSellout(int activityID, int goodsID, String goodsFormat,
                                              int number) {
        // TODO Auto-generated method stub
        String hql = "update ActivityPrice ap set ap.sellOut = ap.sellOut + ?"
                     + "where ap.activityID = ? and ap.goodsID = ? and ap.format = ?";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, number);
            query.setParameter(1, activityID);
            query.setParameter(2, goodsID);
            query.setParameter(3, goodsFormat);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean updateActivityGoodsSellout(int activityID, int skuID, int number) {
        // TODO Auto-generated method stub
        String hql = "update ActivityPrice ap set ap.sellOut = ap.sellOut + ?"
                     + "where ap.activityID = ? and ap.skuID = ?";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, number);
            query.setParameter(1, activityID);
            query.setParameter(2, skuID);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // public boolean updateActivityGoodsSellout(int activityID, int goodsID,
    // String goodsFormat, int number) {
    // // TODO Auto-generated method stub
    // return false;
    // }

    public boolean addShopNews(ShopNews news) {
        news.setOpTime(System.currentTimeMillis());// 设置时间
        try {
            getHibernateTemplate().persist(news);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @SuppressWarnings("rawtypes")
    public ShopNews getShopNews(int shopID, int userID) {
        List list = this.getHibernateTemplate().find(
            "from ShopNews sn where sn.shopID =? and sn.fromID = ? order by sn.opTime desc",
            new Object[] { shopID, userID });
        if (list.size() > 0) {
            return (ShopNews) list.get(0);
        }
        return null;
    }

    public boolean cancelOrder(int orderID) {
        // TODO Auto-generated method stub
        String hql = "update Order orde set orde.station = ? where orde.orderID = ? and orde.station= 1";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, 0);
            query.setParameter(1, orderID);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean addSellout(SelloutRecord selloutRecord) {
        // TODO Auto-generated method stub
        selloutRecord.setOpTime(System.currentTimeMillis());// 设置时间
        try {
            getHibernateTemplate().persist(selloutRecord);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @SuppressWarnings("rawtypes")
    public boolean selloutRecordExist(int goodsID) {
        // TODO Auto-generated method stub
        List list = this.getHibernateTemplate().find("from SelloutRecord sr where sr.goodsID =?",
            new Object[] { goodsID });
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    public boolean updateSelloutRecord(int goodsID, int number, float fee) {
        // TODO Auto-generated method stub
        String hql = "update SelloutRecord sr set  sr.number = sr.number +?,sr.fee= sr.fee + ?  where sr.goodsID = ?";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, number);
            query.setParameter(1, fee);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @SuppressWarnings("rawtypes")
    public int orderNumber(int userID, int station) {
        // TODO Auto-generated method stub
        List list = this.getHibernateTemplate().find(
            "from Order orde where orde.userID =? and orde.station = ?",
            new Object[] { userID, station });
        return list.size();
    }

    @SuppressWarnings("rawtypes")
    public int unFinishedRefund(int userID) {
        // int station=2;//退款完成
        List list = this.getHibernateTemplate().find(
            "from Refund re where re.userID =? and (re.station =0 or re.station=1)",
            new Object[] { userID });
        return list.size();
    }

    @SuppressWarnings("rawtypes")
    public Refund getRefund(int orderID) {
        List list = this.getHibernateTemplate().find("from Refund refund where refund.orderID =? ",
            new Object[] { orderID });
        if (list.size() > 0) {
            return (Refund) list.get(0);
        }
        return null;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public List<String> distinctNumberInCart(final String[] cartIDs) {
        // TODO Auto-generated method stub
        final String SQL = "SELECT DISTINCT(CART.GOODS_ID) from FLAVOR_CART CART WHERE CART.CART_ID IN (:alist) ";
        List<String> list = this.getHibernateTemplate().execute(new HibernateCallback<List>() {
            public List doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery(SQL);
                query.setParameterList("alist", cartIDs);
                return query.list();
            }
        });
        return list;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public int goodsNumberInCart(final int goodsID, final String[] cartIDs) {
        // TODO Auto-generated method stub
        final String SQL = "SELECT SUM(CART.AMOUNT) from FLAVOR_CART CART WHERE CART.GOODS_ID = ? AND CART.CART_ID IN (:alist) ";
        List<String> list = this.getHibernateTemplate().execute(new HibernateCallback<List>() {
            public List doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery(SQL);
                query.setParameter(0, goodsID);
                query.setParameterList("alist", cartIDs);
                return query.list();
            }
        });
        if (list.size() == 0) {
            return 0;
        } else {
            Object obj = list.get(0);
            return Integer.parseInt(obj.toString());
        }
        // return list.size();
    }

    @SuppressWarnings("rawtypes")
    public OrderContent getActivityOrderContent(int goodsID, String goodsFormat, int orderID) {
        List list = this.getHibernateTemplate().find(
            "from OrderContent oc where oc.goodsID =? and oc.goodsFormat = ? and oc.orderID =?",
            new Object[] { goodsID, goodsFormat, orderID });
        if (list.size() > 0) {
            return (OrderContent) list.get(0);
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public List<Order> activityOrder(long startTime, long endTime, int userID) {
        // TODO Auto-generated method stub
        List<Order> list = this.getHibernateTemplate().find(
            "from Order orde where orde.userID =? and orde.opTime >= ? and orde.opTime <=?",
            new Object[] { userID, startTime, endTime });
        return list;
    }

    @SuppressWarnings("unchecked")
    public List<Order> getOrderListbyStation(final long startTime, final long endTime,
                                             final int station) {
        String tempHQL = "from Order orde where orde.STATION =? and orde.opTime >= ? and orde.opTime <=?";
        final String HQL = tempHQL;
        @SuppressWarnings("rawtypes")
        List<Order> list = this.getHibernateTemplate().execute(new HibernateCallback<List>() {
            public List doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createQuery(HQL);
                query.setParameter(0, station);
                query.setParameter(0, startTime);
                query.setParameter(0, endTime);
                return query.list();
            }
        });
        return list;
    }

    public boolean updateActivityGoodsNumber(int activityID, int goodsID, String goodsFormat,
                                             int number) {
        // TODO Auto-generated method stub
        String hql = "update ActivityPrice ap set ap.number = ap.number - ?"
                     + "where ap.activityID = ? and ap.goodsID = ? and ap.format = ?";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, number);
            query.setParameter(1, activityID);
            query.setParameter(2, goodsID);
            query.setParameter(3, goodsFormat);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean reduceActivityNumber(int activityID, int skuID, int number) {
        final String SQL = "update flavor_activity_price ap set ap.AMOUNT = ap.AMOUNT - ?"
                           + "where ap.activityID = ? and ap.skuID = ?";
        Session session = getSession();
        Query query = session.createSQLQuery(SQL);
        query.setParameter(0, number);
        query.setParameter(1, activityID);
        query.setParameter(2, skuID);
        int rows = query.executeUpdate();
        if (rows == 1) {
            return true;
        } else {
            return false;
        }
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public int getStoreHouse(final int shopID) {
        // TODO Auto-generated method stub
        final String SQL = "SELECT HOUSE.OWNER_ID from FLAVOR_STOREHOUSE HOUSE LEFT join FLAVOR_SHOP SHOP "
                           + "ON HOUSE.USER_ID = SHOP.BUSSINESS_ID WHERE SHOP.SHOP_ID= ?";
        List<String> list = this.getHibernateTemplate().execute(new HibernateCallback<List>() {
            public List doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery(SQL);
                query.setParameter(0, shopID);
                return query.list();
            }
        });
        if (list.size() == 0) {
            return 0;
        } else {
            Object obj = list.get(0);
            return Integer.parseInt(obj.toString());
        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public int getShopID(final int bussinessID) {
        // TODO Auto-generated method stub
        final String SQL = "SELECT SHOP.SHOP_ID from FLAVOR_SHOP SHOP WHERE SHOP.BUSSINESS_ID= ?";
        List<String> list = this.getHibernateTemplate().execute(new HibernateCallback<List>() {
            public List doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery(SQL);
                query.setParameter(0, bussinessID);
                return query.list();
            }
        });
        if (list.size() == 0) {
            return 0;
        } else {
            Object obj = list.get(0);
            return Integer.parseInt(obj.toString());
        }
    }

    public ThGroupBuying groupAdd(OrderContent content, ThGroupBuyingRules rule, int userId) {
        ThGroupBuying group = new ThGroupBuying();
        group.setGoodsId(content.getGoodsID());
        group.setGroupBuyingRulesId(content.getActivityID());
        group.setGroupCaptain(userId);
        group.setGroupJoinPeople(1);
        group.setGroupPeople(rule.getGroupPeople());
        group.setEndAt(rule.getEndingAt());

        try {
            getHibernateTemplate().save(group);
        } catch (Exception e) {
            return null;
        }
        return group;
    }

    // 已经参加的正在进行中的团购订单
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public List<BigInteger> groupOrderGet(final int userID, final int groupRuleId) {
        // TODO Auto-generated method stub
        final String SQL = "SELECT CONTENT.GOODS_ID from FLAVOR_ORDER_CONTENT CONTENT LEFT join FLAVOR_ORDER OD "
                           + "ON CONTENT.ORDER_ID = OD.ORDER_ID LEFT JOIN TH_GROUP_BUYING gb ON gb.id = CONTENT.GROUP_ID WHERE OD.USER_ID= ? and CONTENT.ACTIVITY_ID = ? "
                           + "and CONTENT.ACTIVITY_NAME = 'ThGroupBuyingRules' and OD.STATION >= 2 and gb.state < 2";
        List<BigInteger> list = this.getHibernateTemplate().execute(new HibernateCallback<List>() {
            public List doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery(SQL);
                query.setParameter(0, userID);
                query.setParameter(1, groupRuleId);
                return query.list();
            }
        });
        return list;
    }

    public boolean decreaseStocks(ThGroupBuyingRules rule, int num) {
        String hql = "update ThGroupBuyingRules rules set rules.goodsStock = rules.goodsStock - ? "
                     + " where rules.id = ? ";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, num);
            query.setParameter(1, rule.getId());
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean increaseSellout(int groupRuleId, int num) {
        String hql = "update ThGroupBuyingRules rules set rules.goodsSaleNum = rules.goodsSaleNum + ? "
                     + " where rules.id = ? ";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, num);
            query.setParameter(1, groupRuleId);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // 回滚库存
    public boolean rollbackStocks(int rulesID, int num) {
        String hql = "update ThGroupBuyingRules rules set rules.goodsStock = rules.goodsStock + ? "
                     + "where rules.id = ? ";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, num);
            query.setParameter(1, rulesID);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // 回滚疯抢库存
    public boolean rollbackPanicStocks(int panicID, int goodsID, String format, int num) {
        // TODO Auto-generated method stub
        String hql = "update ActivityPrice ap set ap.number = ap.number + ? "
                     + "where ap.activityID = ? and ap.goodsID = ? and ap.format = ?";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, num);
            query.setParameter(1, panicID);
            query.setParameter(2, goodsID);
            query.setParameter(3, format);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // 减少疯抢库存
    public boolean decreasePanicStocks(int panicID, int goodsID, String format, int num) {
        // TODO Auto-generated method stub
        String hql = "update ActivityPrice ap set ap.number = ap.number - ? "
                     + "where ap.activityID = ? and ap.goodsID = ? and ap.format = ?";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, num);
            query.setParameter(1, panicID);
            query.setParameter(2, goodsID);
            query.setParameter(3, format);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public ThGroupBuying groupUpdate(ThGroupBuying group) {
        try {
            getHibernateTemplate().update(group);
        } catch (Exception e) {
            return null;
        }
        return group;
    }

    public boolean orderContentGroupIdAdd(OrderContent content) {
        try {
            getHibernateTemplate().update(content);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public boolean orderContentUpdate(OrderContent content) {
        try {
            getHibernateTemplate().update(content);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    // 删除团购
    public boolean groupDel(int groupID) {
        String hql = "update ThGroupBuying gb set gb.state = ? where gb.id = ? and state = 0";
        try {
            Query query = getSession().createQuery(hql);
            query.setParameter(0, 5);
            query.setParameter(1, groupID);
            int temp = query.executeUpdate();
            if (temp == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public BigDecimal orderSubUnderwritingTotalFee(final int orderId) {
        // 排除掉超值量贩、疯抢、团购后的总价
        final String SQL = "select sum(oc.fee) from flavor_order_content oc left join flavor_goods g on oc.goods_id = g.goods_id where oc.order_id = ? and g.goods_type != 11 and oc.ACTIVITY_NAME = 'ThGoods'";
        List<?> list = this.getHibernateTemplate().execute(new HibernateCallback<List>() {
            public List doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery(SQL);
                query.setParameter(0, orderId);
                return query.list();
            }
        });

        if (list.get(0) != null) {
            return (BigDecimal) list.get(0);
        }
        return BigDecimal.valueOf(0);
    }

    public int closedOrderCount(final int userId) {
        long fourTeenDays = 7 * 24 * 60 * 60 * 1000l;
        final long time = System.currentTimeMillis() - fourTeenDays;

        final String SQL = "SELECT COUNT(od.ORDER_ID) from FLAVOR_ORDER od LEFT join FLAVOR_ORDER_TIME ot on od.ORDER_ID = ot.ORDER_ID where (od.station = 5 or od.station = 6) and ot.TIME_CLIENT_CONFIRM < ? and od.user_id = ?";
        List<?> list = this.getHibernateTemplate().execute(new HibernateCallback<List>() {
            public List doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery(SQL);
                query.setParameter(0, time);
                query.setParameter(1, userId);
                return query.list();
            }
        });
        return ((BigInteger) list.get(0)).intValue();
    }

    public boolean isPriceSame(final String price, final String skuId) {
        final String SQL = "select goods_price from th_sku where id = ?";
        Session session = getSession();
        Query query = session.createQuery(SQL);
        query.setParameter(0, skuId);
        List<?> list = query.list();
        releaseSession(session);
        if (list.size() > 0) {
            float nowPrice = Float.parseFloat((String) list.get(0));
            if (nowPrice != Float.parseFloat(price)) {
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    public ActivityPrice getActivityPriceBySkuID(int skuID) {
        long cTime = System.currentTimeMillis();
        List list = this.getHibernateTemplate().find(
            "from ActivityPrice ap where ap.skuID =? and ap.startTime<=? and ap.endTime>=?",
            new Object[] { skuID, cTime, cTime });
        if (list.size() > 0) {
            return (ActivityPrice) list.get(0);
        }
        return null;
    }

    public List<JsonOrder> ordersadd(List<Cart> cartList, int userID, int addressID, int selfAddID) {

        //【1】事务管理
        List<JsonOrder> returnList = new ArrayList<JsonOrder>();
        Session session = getSessionFactory().getCurrentSession();
        Transaction transaction = session.beginTransaction();

        try {
            //【2】拼单
            List<List<CSG>> orderList = sameCsg(cartList);

            //【3】生成订单
            for (List<CSG> orderCSG : orderList) {

                //【3.1】初始化订单记录
                Order order = createOrder(orderCSG, userID);

                if (addressID != 0 || selfAddID != 0)// 有地址
                    orderManager.addOrder(order);// 插入订单

                //【3.2】保存订单提交时间
                OrderTime oTime = new OrderTime();
                oTime.setOrderID(order.getOrderID());
                orderManager.addOrderTime(oTime);// 插入订单时间

                //【3.3】创建订单物流
                OrderLogistic logistic = createOrderLogistic(order.getOrderID(), orderCSG,
                    addressID, selfAddID);

                //【3.4】查询内容信息
                List<OrderContent> contentList = orderContentAdd(order.getOrderID(), orderCSG);

                //【3.5】保存订单
                if (addressID != 0 || selfAddID != 0) {

                    // 【3.5.2】插入物流
                    orderManager.addOrderLogistic(logistic);

                    // 【3.5.3】计算本次订单的总费用
                    float orderFee = 0;//订单总费用
                    double feeDirector = 0.00;//董事特权费用
                    //查询用户级别和可享受抵扣额度
                    MemberDeductibleInfo info = membershipManager.getDeductible(userID);
                    for (OrderContent content : contentList) {
                        ThSku sku = goodsManager.skuGet(content.getSkuID());
                        if (content.getActivityID() == 0) {
                            //普通商品
                            orderFee += content.getFee();

                            //这里要修改
                            feeDirector += (sku.getProfitShare() * (info.getDeductible()))
                                           * content.getGoodsNumber() / 100.0;
                        } else if (content.getActivityID() != 0) {
                            //团购商品
                            orderFee += content.getFee();
                            //创建团购
                            startGroup(userID, content);
                        }
                    }
                    order.setFee(orderFee + logistic.getFee() - feeDirector);
                    order.setFeeDirector(feeDirector);

                    //【3.5.4】修改订单的价格(商品费用+物流费用-董事特权费用)
                    orderManager.updateOrderFee(order.getOrderID(),
                        (orderFee + logistic.getFee() - feeDirector));

                    //【3.5.5】修改订单优惠价格
                    orderManager.updateOrderFeeDirector(order.getOrderID(), feeDirector);

                    //【3.5.6】保存订单内容
                    for (OrderContent content : contentList) {
                        orderManager.addOrderContent(content);
                    }
                }

                JsonOrder jo = new JsonOrder();
                jo.setOrder(order);
                jo.setOrderContent(contentList);
                jo.setOrderLogistic(logistic);
                returnList.add(jo);
            }
        } catch (Exception e) {
            returnList = null;
            transaction.rollback();
            logger.error(e);
        }

        return returnList;
    }

    //订单生成步骤 
    //【1】根据购物车ID，得到csg的列表【2】csg去重，分成两类，一类是不重复的csg集合，一类是重复的csg集合
    //【3】根据不重复的csg集合获取出可以拼单的csg集合【4】在拼单的csg集合里面添加重复的csg集合 【5】根据快递种类分
    private List<List<CSG>> sameCsg(List<Cart> cartList) {
        // 第一步
        List<CSG> csgList = generateCSG(cartList);// 创建CSG的集合，这是所有的购物车的列表
        // 第二步
        Set<CSG> hs = new HashSet<CSG>();
        hs.addAll(csgList);
        // 所有可以拼包的订单
        List<List<CSG>> samePin = OrderRule.samePin(hs);
        System.out.println("圈子大小---》" + samePin.size());
        // 所有其余相同的shopID地址的商家
        List<List<CSG>> sameShop = OrderRule.sameShop(csgList, hs);
        System.out.println("剩余相同商店大小---》" + sameShop.size());
        // 将其余的相同的shopID的商家的订单加到一起融合生成的订单
        List<List<CSG>> orderList = OrderRule.combineOrder(samePin, sameShop);
        // 根据快递类型分
        orderList = OrderRule.logisticOrder(orderList, logiManager);
        System.out.println("订单大小---》" + orderList.size());
        return orderList;
    }

    private List<CSG> generateCSG(List<Cart> cartList) {
        List<CSG> list = new ArrayList<CSG>();
        for (Cart cart : cartList) {

            if (cart == null)
                break;

            CSG GN = new CSG();
            GN.setGoodsID(cart.getGoodsID());
            GN.setCartID(cart.getCartID());
            GN.setShopID(cart.getShopID());
            int pinID = orderManager.getStoreHouse(cart.getShopID());
            GN.setPinID(pinID);// 拼ID是需要获取的
            list.add(GN);
        }
        return list;
    }

    // 创建物流订单
    private Order createOrder(List<CSG> list, int userID) {
        Order order = new Order();
        /**
         * 如果只有一个商家，则不需要拼单，反之设置为拼单 就是判断所有的shopID是否都相等，
         */
        boolean pinTag = true;
        List<Integer> shopIDList = new ArrayList<Integer>();
        for (CSG csg : list) {
            shopIDList.add(csg.getShopID());
        }

        int shopID = shopIDList.get(0);
        // int pinID = shopIDList.get(0);
        for (CSG csg : list) {
            if (shopID != csg.getShopID()) {
                pinTag = false;
                break;
            }
        }

        if (pinTag) {
            order.setPin(0);// 全部为一个商家，不需要拼包
            order.setShopID(shopID);
        } else {
            order.setPin(1);// 不同的商家，需要拼包
            // order.setShopID(pinID);
            int pinID = orderManager.getStoreHouse(shopID);
            shopID = orderManager.getShopID(pinID);
            order.setShopID(shopID);
        }
        order.setStation(0);// 设置订单状态
        order.setUserID(userID);// 用户ID

        return order;
    }

    private List<OrderContent> orderContentAdd(int orderID, List<CSG> list) {
        List<OrderContent> contentList = new ArrayList<OrderContent>();
        for (CSG csg : list) {
            OrderContent content = new OrderContent();
            Goods goods = goodsManager.goodsDetail(csg.getGoodsID());
            Cart cart = cartManager.cartDetail(csg.getCartID());
            Shop shop = goodsManager.shopDetail(csg.getShopID());

            content.setGoodsID(goods.getGoodsID());
            ThSku sku = goodsManager.skuGet(cart.getSkuID());
            content.setSkuID(cart.getSkuID());

            //普通商品，团购活动商品，之前的活动商品他们之间只存在商品价格，活动编号，活动名称的差异
            double price = 0;
            if (cart.getActivityID() > 0) {
                content.setActivityID(cart.getActivityID());
                content.setActivityName(cart.getActivityName());
                if ("ThGroupBuyingRules".equals(cart.getActivityName())) {
                    //社区团购
                    ThGroupBuyingRules rule = goodsManager.groupBuyingRuleGet(cart
                        .getGroupRulesID());
                    price = orderContentAddForGroup(rule, cart.getNumber(), sku);
                } else {
                    //普通活动
                    ActivityPrice ap = orderManager.getActivityPriceBySkuID(cart.getSkuID());
                    if (ap != null) {
                        price = ap.getStartPrice();
                    } else {
                        // 根据规格获取价格
                        price = sku.getPrice();
                    }
                }

            } else {
                content.setActivityID(0);
                content.setActivityName("ThGoods");
                price = sku.getPrice();
            }

            float fee = (float) (Math.round((cart.getNumber() * price) * 100)) / 100;// 输出123.24;
            content.setFee(fee);

            content.setGoodsTitle(goods.getGoodsTitle());
            content.setGoodsNumber(cart.getNumber());
            content.setShopName(shop.getShopName());
            content.setGoodsFormat(cart.getGoodsFormat());
            content.setGoodsPrice(price);
            content.setGoodsPicture(GoodsParse.getOneGoodsPicture(goods.getGoodsPicture()));
            content.setGoodsFlavor(cart.getGoodsFlavor());// 添加口味
            content.setOrderID(orderID);
            content.setShopID(shop.getShopID());
            contentList.add(content);
            content.setGroupID(cart.getGroupID());
            content.setDirectID(cart.getDirectID());
            content.setGroupRulesID(cart.getGroupRulesID());
        }
        return contentList;
    }

    // 创建订单物流
    private OrderLogistic createOrderLogistic(int orderID, List<CSG> list, int addressID,
                                              int selfAddID) {
        OrderLogistic logistic = new OrderLogistic();

        //普通地址
        if (addressID != 0) {
            DeliveryAddr delivery = accountManager.getAddr(addressID);
            if (delivery != null) {
                logistic = addLogistic(list, delivery);
                // logistic.setAddressID(addressID);
            }
        }
        //自提地址
        if (selfAddID != 0) {
            ThGroupDeliveryAddr addr = directoryManager.getGroupDeliveryInfoById(selfAddID);
            if (addr != null) {
                logistic.setFee(0);
                ThDirectSupply supply = directoryManager.getDirectSupplyById(addr
                    .getDirectSupplyId() + "");
                logistic.setFromAddress(supply.getPickupPoint());
                logistic.setReceiver(addr.getName());// 收货人姓名
                logistic.setReceiverPhone(addr.getPhone());// 收货人手机号
                logistic.setReceiverAddress(supply.getBlockName() + addr.getAddress());
                logistic.setWeight("0");

                float allWeight = 0;// 商品的重量
                // 先计算商品的总重量和商品的总价格
                for (CSG csg : list) {
                    Cart cart = cartManager.cartDetail(csg.getCartID());
                    ThSku sku = goodsManager.skuGet(cart.getSkuID());
                    int number = cart.getNumber();// 商品数量
                    allWeight += number * (sku.getWeight());// 商品的总重量
                }
                logistic.setWeight(allWeight + "");
            }
        }
        logistic.setOrderID(orderID);
        return logistic;
    }

    // 创建订单的物流
    private OrderLogistic addLogistic(List<CSG> list, DeliveryAddr addr) {
        OrderLogistic ol = new OrderLogistic();
        float minPostage = 10000000;// 最低邮费(这是先设定的)

        float allFee = 0;// 所有费用
        float allWeight = 0;// 商品的重量

        // 先计算商品的总重量和商品的总价格
        for (CSG csg : list) {
            Cart cart = cartManager.cartDetail(csg.getCartID());
            ThSku sku = goodsManager.skuGet(cart.getSkuID());
            int number = cart.getNumber();// 商品数量
            double price = 0;
            if (cart.getActivityName().equals("ThPanicBuyingSku")) {
                ActivityPrice panicPrice = orderManager.getActivityPriceBySkuID(cart.getSkuID());
                if (panicPrice == null) {
                    price = sku.getPrice();// 商品价格
                } else {
                    price = panicPrice.getStartPrice();// 秒杀价格
                }
            } else {
                price = sku.getPrice();// 商品价格
            }
            double goodsFee = number * price;// 商品的费用

            allFee += goodsFee;// 总价格
            allWeight += number * (sku.getWeight());// 商品的总重量
        }

        // 取最小的邮费
        for (CSG csg : list) {
            Goods goods = goodsManager.goodsDetail(csg.getGoodsID());
            int patternID = goods.getGoodsLogistic();// 物流模版ID
            float postage = postageCaculate(allFee, allWeight, patternID, addr);
            if (postage == 0) {
                minPostage = 0;// 已经免费了,就不需要再计算下去了
                break;
            }
            if (postage <= minPostage) {
                minPostage = postage;
            }
        }

        // 设置邮费
        ol.setFee(minPostage);

        String fromAddress = "北京市金融街园中园";
        ol.setFromAddress(fromAddress);

        ol.setReceiver(addr.getName());// 收货人姓名
        ol.setReceiverPhone(addr.getPhone());// 收货人手机号

        String county = "";
        if (addr.getCounty() != null) {
            county = addr.getCounty();// 防止县为空
        }

        String receiverAddress = addr.getProvince() + addr.getCity() + county + addr.getAddress();
        ol.setReceiverAddress(receiverAddress);

        ol.setWeight(allWeight + "");
        return ol;
    }

    private int postageCaculate(float allMoney, float allWeight, int patternID, DeliveryAddr addr) {
        /*
         * 是否存在包邮 1:存在，且达到包邮的条件 运费为 0； 2: 达不到条件的情况下查看是否是其他区域的计算方式 2.1
         * 是其他区域，根据其他区域计算邮费 2.2 不是其他区域就是全国的计算方式计算邮费
         */

        float mailFee;
        // 包邮的地区
        AreaPostage ap = logiManager.getPostage(patternID, addr.getProvince(), addr.getCity());
        AreaPostage apNation = null;
        if (ap != null) {
            mailFee = ap.getPostage();// 其他区域模版
        } else {
            AreaPostage apNO = logiManager.getNoPostage(patternID, addr.getProvince(),
                addr.getCity());
            if (apNO != null) {
                mailFee = -1;// 不包邮
            } else {
                apNation = logiManager.getNationPostage(patternID);
                if (apNation != null) {
                    mailFee = apNation.getPostage();// 全国模版
                } else {
                    mailFee = -1;// 不包邮
                }
            }
        }
        if (mailFee == -1 || mailFee > allMoney) {// 不包邮的情况下
            // 无法包邮
            LogisticPatternExc logiExc = logiManager.getPatternExc(patternID, addr.getProvince(),
                addr.getCity());
            if (logiExc != null) {
                return weightCostNoPostage(logiExc.getInitKG(), logiExc.getInitFee(),
                    logiExc.getAddKG(), logiExc.getAddFee(), allWeight);
            } else {
                LogisticPattern logi = logiManager.getPattern(patternID);
                return weightCostNoPostage(logi.getInitKG(), logi.getInitFee(), logi.getAddKG(),
                    logi.getAddFee(), allWeight);
            }
        } else {
            // //允许包邮
            // LogisticPatternExc logiExc = logiManager.getPatternExc(patternID,
            // addr.getProvince(), addr.getCity());
            // if(logiExc!=null){
            // return weightCostWithPostage(logiExc.getInitKG(),
            // logiExc.getInitFee(), logiExc.getAddKG(),logiExc.getAddFee(),
            // allWeight);
            // }else{
            // LogisticPattern logi = logiManager.getPattern(patternID);
            // return weightCostWithPostage(logi.getInitKG(), logi.getInitFee(),
            // logi.getAddKG(),logi.getAddFee(), allWeight);
            // }

            if (ap != null) {
                return weightCostWithPostage(ap.getInitKG(), ap.getAddKG(), ap.getAddFee(),
                    allWeight);
            } else {
                return weightCostWithPostage(apNation.getInitKG(), apNation.getAddKG(),
                    apNation.getAddFee(), allWeight);
            }

        }

        // System.out.println("---包邮费用---"+mailFee);
        // if(ap!=null&&ap.getPostage()<allMoney){
        // return 0;
        // }
        //
        // LogisticPatternExc logiExc = logiManager.getPatternExc(patternID,
        // addr.getProvince(), addr.getCity());
        // if(logiExc!=null){
        // return weightCost(logiExc.getInitKG(), logiExc.getInitFee(),
        // logiExc.getAddKG(),logiExc.getAddFee(), allWeight);
        // }else{
        // LogisticPattern logi = logiManager.getPattern(patternID);
        // return weightCost(logi.getInitKG(), logi.getInitFee(),
        // logi.getAddKG(),logi.getAddFee(), allWeight);
        // }

    }

    private double orderContentAddForGroup(ThGroupBuyingRules rule, int num, ThSku sku) {
        double price = 0;

        //判断是否为阶梯费用
        if (rule.getIsLadderPrice() == 0) {
            //不执行阶梯价格
            price = sku.getPrice();
        } else {
            //执行阶梯价格
            int groupJoinPeople = 0; //参团人数
            ThGroupBuying group = goodsManager.groupBuyingGetByRulesId(rule.getId());
            //首次开团
            if (group != null) {
                groupJoinPeople = group.getGroupJoinPeople();
            }

            //判断当前团购人数属于哪个区间
            if (groupJoinPeople < rule.getLevel2Num()) {
                price = Double.parseDouble(sku.getLevel1Price());
            } else if (groupJoinPeople >= rule.getLevel2Num()
                       && groupJoinPeople < rule.getLevel3Num()) {
                price = Double.parseDouble(sku.getLevel2Price());
            } else if (groupJoinPeople >= rule.getLevel3Num()) {
                price = Double.parseDouble(sku.getLevel3Price());
            }
        }
        return price;//支付费用
    }

    // 有包邮重量消费重量消费
    private int weightCostWithPostage(float initKG, float addKG, float addFee, float goodsWeight) {
        float price = 0;
        float goodsKG = goodsWeight / 1000;// 克转化为千克
        if (goodsKG < initKG) {
            price = 0;
        } else {
            int iKG = (int) Math.ceil(goodsKG);
            price = ((iKG - initKG) / addKG) * addFee;
        }
        return (int) price;
    }

    // 无免邮重量消费
    private int weightCostNoPostage(float initKG, float initFee, float addKG, float addFee,
                                    float goodsWeight) {
        float price = 0;
        float goodsKG = goodsWeight / 1000;// 克转化为千克
        if (goodsKG < initKG) {
            price = initFee;
        } else {
            int iKG = (int) Math.ceil(goodsKG);
            price = initFee + ((iKG - initKG) / addKG) * addFee;
        }
        return (int) price;
    }

    // 开启团购(修改商品的库存，删除购物车，增加售出件数)
    private int startGroup(int userID, OrderContent content) {
        //要判断用户的下单是一个开团还是参团，就要看其中的group_id字段，如果等于0，就是开新团
        ThGroupBuying group = goodsManager.groupBuyingGetByRulesId(content.getActivityID());
        //首次开团
        if (content.getActivityName().equals("ThGroupBuyingRules") && group == null) {
            ThGroupBuyingRules rule = goodsManager.groupBuyingRuleGet(content.getActivityID());
            //扣库存(这里改成去掉sku中库存)
            //goodsManager.reduceSkuStock(content.getSkuID(), content.getGoodsNumber());
            //增加销量
            goodsManager.updateSkuSellOut(content.getSkuID(), content.getGoodsNumber());
            //if (StockFlag) {
            ThGroupBuying TGB = orderManager.groupAdd(content, rule, userID);
            if (TGB != null) {
                content.setGroupID(TGB.getId());
                //boolean updateFlag = orderManager.orderContentGroupIdAdd(content);
                //System.out.println("更新订单团购id" + TGB.getId() + "是否成功" + updateFlag);
                return 1;
            } else {
                return -10;
            }
            /*} else {
                return -11;
            }*/
        } else {
            content.setGroupID(group.getId());
            //orderManager.orderContentGroupIdAdd(content);
            //扣库存(这里改成去掉sku中库存)
            /* goodsManager.reduceSkuStock(content.getSkuID(), content.getGoodsNumber());*/
            goodsManager.updateSkuSellOut(content.getSkuID(), content.getGoodsNumber());
            /*if (StockFlag) {
                // 原来的商品要添加销量
                goodsManager.updateSellOut(content.getGoodsID(), content.getGoodsNumber());
            } else {
                return -11;
            }*/
        }
        return 1; // 正常团购只有一个订单,所以直接在这里结束
    }

    public CartManager getCartManager() {
        return cartManager;
    }

    public void setCartManager(CartManager cartManager) {
        this.cartManager = cartManager;
    }

    public OrderManager getOrderManager() {
        return orderManager;
    }

    public void setOrderManager(OrderManager orderManager) {
        this.orderManager = orderManager;
    }

    public LogisticManager getLogiManager() {
        return logiManager;
    }

    public void setLogiManager(LogisticManager logiManager) {
        this.logiManager = logiManager;
    }

    public GoodsManager getGoodsManager() {
        return goodsManager;
    }

    public void setGoodsManager(GoodsManager goodsManager) {
        this.goodsManager = goodsManager;
    }

    public AccountManager getAccountManager() {
        return accountManager;
    }

    public void setAccountManager(AccountManager accountManager) {
        this.accountManager = accountManager;
    }

    public AccountDAO getaDAO() {
        return aDAO;
    }

    public void setaDAO(AccountDAO aDAO) {
        this.aDAO = aDAO;
    }

    /**
     * @param membershipManager the membershipManager to set
     */
    public void setMembershipManager(MembershipManager membershipManager) {
        this.membershipManager = membershipManager;
    }

}
